<?php

namespace app\service;

use app\exception\ErrnoPlus;
use app\model\VersionInfoModel;
use app\service\cache\SendNoticeTableCacheService;
use app\service\cache\VersionInfoCacheService;
use ArrayObject;
use share\exception\ApiException;
use share\service\BaseModelService;
use share\utils\Helper;

class VersionInfoService extends BaseModelService
{
    public static function getModel(){
        return new VersionInfoModel;
    }
  

    public static function getLastVersionInfoByFilter($filter){
        $versioInfo = VersionInfoCacheService::getOneByFilter($filter, ["version", "desc"]);
        if (empty($versioInfo)) {
           return null;
        }
        $res = [
            "type" => $versioInfo['type'],
            "name" => $versioInfo['name'],
            "language" => $versioInfo['language'],
            "version" => $versioInfo['version'],
            "showVersion" => $versioInfo['version_show'],
            "md5" => $versioInfo['md5'],
            "uri" => $versioInfo['uri'],
            "force" => $versioInfo['force'],
            "upgrade" => $versioInfo['upgrade'],
            "logs" => $versioInfo['logs'],
            "upgradeVersion" => 0,
            "upgradeType" => $versioInfo['upgrade_type'],
            "appStore" => $versioInfo['app_store']
        ];
        $filter['force'] = 1;
        // 如果有需要强制更新的版本  优先使用
        $forceUpdate = VersionInfoCacheService::getOneByFilter($filter, ["version", "desc"]);
        if ($forceUpdate) {
            $res["upgradeVersion"] = $forceUpdate['version'];
        }
        return $res;
    }

    public static function getLastOne($param,$packageName)
    {
        if (empty($packageName) && empty($param['name'])) {
            throw new ApiException("lost param", ErrnoPlus::PARAM_ERROR);
        }
        if (empty($packageName)) {
            $autoPackage = self::getDefaultPackageByVendor($param['name'], $param['type'], $param['language']);
            if (empty($autoPackage)) {
                $realPackage = $param['name'];
            } else {
                $realPackage = $autoPackage;
            }
        } else {
            $realPackage = $packageName;
        }
        $param['name'] = $realPackage;
        $versioInfo = self::getLastVersionInfoByFilter($param);  
        return $versioInfo;
    }

    /**
     * 新增或跟新版本记录
     */
    public static function appUpdate($param)
    {
        $data = self::getByFilter([
            "type" => $param["type"],
            "name" => $param["name"],
            "version" => $param["version"],
            "language" => $param["language"]
        ]);
        if ($data) {
            $update = [];
            foreach ($param as $key => $val) {
                if ($data[$key] !== $val) {
                    $update[$key] = $val;
                }
            }
            if (count($update) > 0) {
                self::update($data['id'], $update);
            }
        } else {
            self::add($param);
        }
        VersionInfoCacheService::reflushAll();
    }

    public static function getSummaryInfo($param,$notifyInfoAsArray = false,$clientType){
        $versionInfo = self::getLastVersionInfoByFilter([
            'type' => strtolower($param["system"]),
            'language' => strtoupper($param["language"]),
            'name' => $param["package"],
        ]);
        $res = [
            "versionInfo" => new ArrayObject(), // 针对老版本 json_encode 后为 [] 时闪退的问题
            "notifyInfo" => [], // 针对老版本 json_encode 后为 [] 时闪退的问题
        ];
        if ($versionInfo) {           
            $res["versionInfo"] = $versionInfo;
        }
        if(!$notifyInfoAsArray){ //针对v2 无数据时返回空
            $res['notifyInfo']  = new ArrayObject();
            
            // unset($res['notifyInfo']);
        }

        $sendInfo = SendNoticeTableCacheService::getOneByFilter(["language" => $param["language"], "status" => 1],["end_time", "desc"]);
        if ($sendInfo) {
            if($notifyInfoAsArray){      
                $res["notifyInfo"] = [
                    [
                        "model" => $sendInfo["model"],
                        "beginTime" => $sendInfo["begin_time"],
                        "endTime" => $sendInfo["end_time"],
                        "level" => $sendInfo["level"],
                        "title" => $sendInfo["title"],
                        "message" => $sendInfo["message"]
                    ]
                ];
            }
            else{
                $res["notifyInfo"] = [
                    "model" => $sendInfo["model"],
                    "beginTime" => $sendInfo["begin_time"],
                    "endTime" => $sendInfo["end_time"],
                    "level" => $sendInfo["level"],
                    "title" => $sendInfo["title"],
                    "message" => $sendInfo["message"]
                ];
            } 
        }
        return $res;
    }

    /**
     * 厂商默认的包
     */
    public static function getDefaultPackageByVendor($vendor, $os, $language = 'CN')
    {
        $data = [
            'ENZ' => [
                'ios' => 'com.enzhi.monitord',
                'android' => [
                    'CN' => 'com.ml.yunmonitord',
                    'default' => 'com.ml.yunmonitorf',
                ]
            ],
            'HDT-TRUECLOUD' => [
                'ios' => 'com.truecloudpro.genx',
                'android' => 'com.truecloudpro.genx',
            ],
            'HDT-LENOVO' => [
                'ios' => 'com.ml.yunlenovoAI',
                'android' => 'com.ml.yunlenovo',
            ],
            'HDT-CK' => [
                'ios' => 'com.ml.yunck',
                'android' => 'com.ml.yunck',
            ],
            'HDT-VAA9' => [
                'ios' => 'com.veisent.VAA9',
                'android' => 'com.wst.VAA9',
            ],
        ];
        $vendorKey = strtoupper($vendor);
        $osKey = strtolower($os);
        $languageKey = strtoupper($language);
        if (isset($data[$vendorKey]) && isset($data[$vendorKey][$osKey])) {
            if (is_array($data[$vendorKey][$osKey])) {
                if (isset($data[$vendorKey][$osKey][$languageKey])) {
                    return $data[$vendorKey][$osKey][$languageKey];
                }
                return $data[$vendorKey][$osKey]["default"];
            } else {
                return $data[$vendorKey][$osKey];
            }
        }
        return null;
    }

    public static function addVersion($param){
        $logInfo = $param['logInfo'];
        unset($param['logInfo']);
        $item = Helper::arrayCamelKeyToUnderscore($param);
        $items = [];
        foreach($logInfo as $log){
            $temp = json_decode(json_encode($item),true);
            $temp['language'] = $log['language'];
            $temp['logs'] = $log['logs'];
            $items[] = $temp;
        }
        self::addBulk($items);
        VersionInfoCacheService::reflushAll();
    }

    public static function updateVersion($param){
        $id = $param['id'];
        unset($param['id']);
        $item = Helper::arrayCamelKeyToUnderscore($param);
        $origin = self::getBase($id);
        if(empty($origin)){
            throw new ApiException("version info is not exist",ErrnoPlus::COMMON_ERROR);
        }
        $update = [];
        foreach($item as $key => $val){
            if($val != $origin[$key]){
                $update[$key] = $val;
            }
        }
        if(count($update) > 0){
            self::update($id,$update);
        }

        VersionInfoCacheService::reflushAll();
    }

    public static function delVersion($id){
        self::del($id);
        VersionInfoCacheService::reflushAll();
    }

    public static function buildCondition($filter){
        $res = [];
        if(isset($filter['type']) && !empty($filter['type'])){
            $res['type'] = $filter['type'];
        }
        if(isset($filter['name']) && !empty($filter['name'])){
            $res['name'] = $filter['name'];
        }
        if(isset($filter['version']) && !empty($filter['version'])){
            $res['version'] = $filter['version'];
        }
        if(isset($filter['versionShow']) && !empty($filter['versionShow'])){
            $res['version_show'] = $filter['versionShow'];
        }
        return $res;
    }
}
